package com.buildings.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.buildings.R;
import com.buildings.api.Api;
import com.buildings.bean.AddressBean;
import com.buildings.bean.DivisionResultBean;
import com.buildings.http.BaseCallBack;
import com.buildings.http.MyHttpClient;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class TabTitleBuilder implements View.OnClickListener {
    LinearLayout llTabTitle;
    private Dialog myDialog;
    private Activity activity;
    //省
    EditText etProvince;
    //市
    EditText etCity;
    //区
    EditText etArea;
    //经度
    EditText etLat;
    //纬度
    EditText etLon;
    //建筑地址
    EditText etBuildingAddress;

    public static final String PROVINCE = "province";
    public static final String CITY = "city";
    public static final String COUNTY = "county";

    private List<DivisionResultBean.Division> provinceList;
    private List<DivisionResultBean.Division> cityList;
    private List<DivisionResultBean.Division> countyList;
    private AddressBean province;
    private AddressBean.CityBean city;
    private String county;

    public String getProvinceStr() {
        return etProvince.getText().toString().trim();
    }

    public String getCityStr() {
        return etCity.getText().toString().trim();
    }

    public String getAreaStr() {
        return etArea.getText().toString().trim();
    }

    public String getLatStr() {
        return etLat.getText().toString().trim();
    }

    public String getLonStr() {
        return etLon.getText().toString().trim();
    }

    public String getBuilderAdressStr() {
        return etBuildingAddress.getText().toString().trim();
    }

    public void setLat(double x) {
        String strX = x + "";
        etLat.setText(strX);
        setBuildingAddress();
    }

    public void setLon(double y) {
        String strY = y + "";
        etLon.setText(strY);
        setBuildingAddress();
    }

    public void setBuildingAddress() {
        if (TextUtils.isEmpty(getLatStr())) {
            return;
        }
        if (TextUtils.isEmpty(getLonStr())) {
            return;
        }
        double lat = Double.parseDouble(getLatStr());
        double lon = Double.parseDouble(getLonStr());
        String address = new GetAddressUtil(activity).getAddress(lat, lon);
        etBuildingAddress.setText(address);
        String province = new GetAddressUtil(activity).getProvince(lat, lon);
        etProvince.setText(province);
        String city = new GetAddressUtil(activity).getCity(lat, lon);
        etCity.setText(city);
        String area = new GetAddressUtil(activity).getArea(lat, lon);
        etArea.setText(area);
        Log.e("wangchao","adress = " + address + " province =" + province + "city = " + city + " area = " + area);

    }

    public TabTitleBuilder(LinearLayout llTabTitle, Activity activity) {
        this.llTabTitle = llTabTitle;
        this.activity = activity;
        initView();
    }

    public void setEnabled() {
        etProvince.setClickable(false);
        etProvince.setEnabled(false);
        etCity.setClickable(false);
        etCity.setEnabled(false);
        etArea.setClickable(false);
        etArea.setEnabled(false);
        etLat.setEnabled(false);
        etLon.setEnabled(false);
        etBuildingAddress.setFocusable(false);
    }

    public void initView() {
        etProvince = llTabTitle.findViewById(R.id.et_province);
        etCity = llTabTitle.findViewById(R.id.et_city);
        etArea = llTabTitle.findViewById(R.id.et_area);
        etLat = llTabTitle.findViewById(R.id.et_lat);
        etLon = llTabTitle.findViewById(R.id.et_lon);
        etBuildingAddress = llTabTitle.findViewById(R.id.et_building_address);
        etProvince.setOnClickListener(this);
        etArea.setOnClickListener(this);
        etCity.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.et_province:
                getDivisions("root", PROVINCE);
                break;
            case R.id.et_city:
                if (TextUtils.isEmpty(etProvince.getText().toString())) {
                    CustomToast.showToast(activity, "请先选择省");
                    return;
                }
                getDivisions("", CITY);
                break;
            case R.id.et_area:
                if (TextUtils.isEmpty(etProvince.getText().toString())) {
                    CustomToast.showToast(activity, "请先选择省");
                    return;
                }
                if (TextUtils.isEmpty(etCity.getText().toString())) {
                    CustomToast.showToast(activity, "请先选择市");
                    return;
                }
                if (null == city) {
                    return;
                }
                getDivisions("", COUNTY);
                break;
        }
    }

    private void getDivisions(String divisionid, final String type) {
        String JsonData = DataUtils.getAddressJson(activity, "province.json");//获取assets目录下的json文件数据
        ArrayList<AddressBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        if (null == jsonBean || jsonBean.size() == 0) {
            Toast.makeText(activity, "地理位置获取失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.equals(PROVINCE, type)) {
            showProvincePickerView(jsonBean, PROVINCE);
        } else if (TextUtils.equals(CITY, type)) {
            for (AddressBean addressBean : jsonBean) {
                if (addressBean.getName().equals(getProvinceStr())) {
                    showPickerView(addressBean.getCityList(), CITY);
                }
            }
        } else if (TextUtils.equals(COUNTY, type)) {
            for (AddressBean addressBean : jsonBean) {
                if (addressBean.getName().equals(getProvinceStr())) {
                    for (AddressBean.CityBean cityBean : addressBean.getCityList()) {
                        if (cityBean.getName().equals(getCityStr())) {
                            showAreaPickerView(cityBean.getArea(), COUNTY);
                        }
                    }
                }
            }
        }

//        String url = Api.GET_LOCATION + "divisions/" + divisionid + "/subdivisions";
//        MyHttpClient
//                .newBuilder()
//                .get()
//                .url(url)
//                .build()
//                .enqueue(new BaseCallBack<DivisionResultBean>() {
//                    @Override
//                    public void onSuccess(DivisionResultBean divisionResultBean) {
//                        super.onSuccess(divisionResultBean);
//                        if (myDialog != null)
//                            myDialog.dismiss();
//                        if (divisionResultBean != null && divisionResultBean.getCode() == 200) {
//                            if (divisionResultBean.getData() != null) {
//                                if (TextUtils.equals(PROVINCE, type)) {
//                                    provinceList = divisionResultBean.getData();
//                                    showPickerView(provinceList, PROVINCE);
//                                } else if (TextUtils.equals(CITY, type)) {
//                                    cityList = divisionResultBean.getData();
//                                    showPickerView(cityList, CITY);
//                                } else if (TextUtils.equals(COUNTY, type)) {
//                                    countyList = divisionResultBean.getData();
//                                    showPickerView(countyList, COUNTY);
//                                }
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        super.onFailure(call, e);
//                        CustomToast.showToast(activity, "网络异常");
//                        if (myDialog != null)
//                            myDialog.dismiss();
//                    }
//
//                    @Override
//                    public void onError(int code) {
//                        super.onError(code);
//                        CustomToast.showToast(activity, "网络异常");
//                        if (myDialog != null)
//                            myDialog.dismiss();
//                    }
//                });
    }

    private void showProvincePickerView(final List<AddressBean> list, final String type) {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(activity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                AddressBean division = list.get(options1);
                switch (type) {
                    case PROVINCE:
                        province = division;
                        city = null;
                        etCity.setText("");
                        etProvince.setText(division.getName());
                        county = null;
                        etArea.setText("");
                        break;
                }
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(list);
        pvOptions.show();
    }

    private void showAreaPickerView(final List<String> list, final String type) {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(activity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String division = list.get(options1);
                county = division;
                etArea.setText(county);
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(list);
        pvOptions.show();
    }

    private void showPickerView(final List<AddressBean.CityBean> list, final String type) {// 弹出选择器（省市区三级联动）
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(activity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                AddressBean.CityBean division = list.get(options1);
                switch (type) {
                    case CITY:
                        city = division;
                        county = null;
                        etArea.setText("");
                        etCity.setText(division.getName());
                        break;
                }
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .setContentTextSize(20)
                .build();
        pvOptions.setPicker(list);
        pvOptions.show();
    }

    public void setDetailText(String province, String city, String area, String lat
            , String lon, String buildingAddress) {
        etProvince.setText(null == province ? "" : province);
        etCity.setText(null == city ? "" : city);
        etArea.setText(null == area ? "" : area);
        etLat.setText(null == lon ? "" : lon);
        etLon.setText(null == lat ? "" : lat);
        etBuildingAddress.setText(null == buildingAddress ? "" : buildingAddress);
    }

    public ArrayList<AddressBean> parseData(String result) {//Gson 解析
        ArrayList<AddressBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                AddressBean entity = gson.fromJson(data.optJSONObject(i).toString(), AddressBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
}
